﻿using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service.Cache;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pay.Service {
    public class ShopInfoService : ServiceBase, IShopInfoService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        private IMerchantService _iMerchantService;
        public ShopInfoService(IUnitOfWork iUnitOfWork, IMerchantService iMerchantService)
            : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
            _iMerchantService = iMerchantService;
        }
        #region 后台管理
        /// <summary>
        /// 获得商家列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedResult<shop_info_dto_ex> GetShopInfos(ShopInfoQuery query) {
            var filter = PredicateBuilder.True<ShopInfo>();
            if (!string.IsNullOrEmpty(query.name)) {
                filter = filter.And(c => c.ShopName == query.name || c.Merchant.Mobile == query.name);
            }
            if (!string.IsNullOrEmpty(query.status)) {
                bool value = int.Parse(query.status) == 1 ? true : false;
                filter = filter.And(c => c.IsDisabled == value);
            }
            if (!string.IsNullOrEmpty(query.begin_time)) {
                long time = DateTime.Parse(query.begin_time).ToUnix();
                filter = filter.And(c => c.CreateTime >= time);
            }
            if (!string.IsNullOrEmpty(query.end_time)) {
                long time = DateTime.Parse(query.end_time).AddDays(1).ToUnix();
                filter = filter.And(c => c.CreateTime <= time);
            }
            var result = context.ShopInfo.FromCachePaged<ShopInfo, shop_info_dto_ex>(query.page, query.size, filter, orderBy => orderBy.OrderByDescending(o => o.IsDisabled).ThenByDescending(o => o.CreateTime));
            return result;
        }
        /// <summary>
        /// 根据Id获取商家信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public shop_info_dto_ex GetShopInfoById(long id) {
            var result = context.ShopInfo.Where(s => s.Id == id).FromCacheFirstOrDefault<ShopInfo, shop_info_dto_ex>();
            if(result != null && result.red_drill_receiver_id != null) {
                var receiver = _iMerchantService.Get(result.red_drill_receiver_id.Value);
                if (receiver != null)
                    result.red_drill_receiver_mobile = receiver.mobile;
            }
            return result;
        }
        /// <summary>
        /// 更新商家状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public int UpdateShopInfoStatus(long id, int status) {
            var model = context.ShopInfo.FindById(id);
            List<string> tags = new List<string>() { "ShopInfo" + model.Id };
            if (status == 0)
                model.IsDisabled = false;
            else if (status == 1)
                model.IsDisabled = true;
            if (model.IsDisabled) {//禁用店铺
                //下架所有自营商品
                var productList = context.Products.Where(o => o.MerchantId == model.Id).ToList();
                if (productList != null && productList.Count() > 0) {
                    tags.Add("Product");
                    List<long> productIds = productList.Select(o => o.Id).ToList();
                    productList.ForEach(o => { o.SaleStatus = SaleStatus.OutOfStock; tags.Add("Peoduct" + o.Id); });
                    //将对应的分销表数据状态改为已失效
                    var distributionProductList = context.DistributionProducts.Where(o => productIds.Contains(o.ProductId) && o.Status != EDistributionProductStatus.Deleted).ToList();
                    if (distributionProductList != null && distributionProductList.Count() > 0) {
                        tags.Add("DistributionProduct");
                        foreach (var dp in distributionProductList) {
                            dp.Status = EDistributionProductStatus.Failure;
                            tags.Add("DistributionProduct" + dp.MerchantId);
                        }
                    }
                }
                //下架该店的分销商品
                var myDistributionProductList = context.DistributionProducts.Where(o => o.MerchantId == model.Id && o.Status != EDistributionProductStatus.Deleted).ToList();
                if (myDistributionProductList != null && myDistributionProductList.Count() > 0) {
                    myDistributionProductList.ForEach(o => { o.Status = EDistributionProductStatus.Failure; });
                    tags.Add("DistributionProduct" + model.Id);
                }
            }

            int result = _iUnitOfWork.Commit(tags.ToArray());
            return result;
        }

        /// <summary>
        /// 更新店铺（红钻交易指向账户）信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public bool UpdateShopInfo(shop_info_dto_ex dto) {
            var model = context.ShopInfo.FindById(dto.id);
            if (!string.IsNullOrEmpty(dto.red_drill_receiver_mobile)) {
                var oem = context.Merchants.FirstOrDefault(c => c.MerchantNo == t_RequestMethod.merchant_no);
                Merchant receiver = context.Merchants.FirstOrDefault(c => c.Mobile == dto.red_drill_receiver_mobile && c.IsOEM == false && c.OemId == oem.Id);//收钻方
                if (receiver == null)
                    throw new ServerErrorException("您输入的红钻交易指向账户不存在");
                model.RedDrillReceiverId = receiver.Id;
            } else {
                model.RedDrillReceiverId = null;
            }

            return _iUnitOfWork.Commit("ShopInfo", "ShopInfo" + dto.id) > 0;
        }
        #endregion

        public List<shop_info_dto> GetShops() {
            var list = context.ShopInfo.FromCache<ShopInfo, shop_info_dto>("ShopInfo");
            return list;
        }
        public shop_info_dto GetShopById(long id) {
            var model = context.ShopInfo.Where(c => c.Id == id).FromCacheFirstOrDefault<ShopInfo, shop_info_dto>("ShopInfo" + id);
            if (model == null) return new shop_info_dto();
            else return model;
        }
        /// <summary>
        /// 获取店铺id
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public long GetShop(long productId, long shopId) {
            long shop_id = shopId;
            if (shopId == 0) {
                var product = context.Products.FirstOrDefault(c => c.Id == productId);
                var shop = context.ShopInfo.FirstOrDefault(c => c.Id == product.MerchantId);
                if (shop != null)
                    shop_id = shop.Id;
            }
            return shop_id;
        }
        public bool Save(shop_info_dto model, bool isSupplierPC = false) {
            var merchant = context.Merchants.FindById(model.id);
            if (!merchant.IsSupplier) { throw new ServerErrorException("您还未开通节点商城"); }
            string[] regionIds = model.region_ids.Split(',').ToArray();
            int regionIdNum = regionIds.Count();
            if (regionIdNum == 1) model.province_id = long.Parse(regionIds[0]);
            else if (regionIdNum == 2) {
                model.province_id = long.Parse(regionIds[0]);
                model.city_id = long.Parse(regionIds[1]);
            } else if (regionIdNum == 3) {
                model.province_id = long.Parse(regionIds[0]);
                model.city_id = long.Parse(regionIds[1]);
                model.area_id = long.Parse(regionIds[2]);
            }
            model.region_id = model.area_id > 0 ? model.area_id : model.city_id;
            List<string> tags = new List<string>();
            int result = 0;
            var shopInfo = context.ShopInfo.FindById(model.id);
            if (shopInfo == null) {
                shopInfo = model.ToDtoObject<ShopInfo>();
                if (isSupplierPC) {
                    shopInfo.FirstCategoriesId = model.first_categories_id;
                    shopInfo.FirstCategoriesName = model.first_categories_name;
                    shopInfo.SecondCategoriesId = model.second_categories_id;
                    shopInfo.SecondCategoriesName = model.second_categories_name;
                }
                shopInfo.CreateTime = DateTime.Now.ToUnix();
                shopInfo.Rate = 0.2M;
                context.ShopInfo.Add(shopInfo);
                result = _iUnitOfWork.Commit();
            } else {
                if (shopInfo.IsDisabled) throw new ServerErrorException("您的店铺已冻结,请联系客服");
                model.ToDtoObject(shopInfo);
                if (isSupplierPC) {
                    shopInfo.FirstCategoriesId = model.first_categories_id;
                    shopInfo.FirstCategoriesName = model.first_categories_name;
                    shopInfo.SecondCategoriesId = model.second_categories_id;
                    shopInfo.SecondCategoriesName = model.second_categories_name;
                }
                tags.Add("ShopInfo" + shopInfo.Id);
            }

            if (merchant.IsSupplier == false) {
                merchant.IsSupplier = true;
                tags.Add("Merchant" + merchant.Id);
                tags.Add("Merchant" + merchant.MerchantNo);
            }
            int r = _iUnitOfWork.Commit(tags.ToArray());
            return result > 0;
        }
    }
}
